﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using MM.DBUtility;

namespace MobileManager
{
    public partial class S1receive : System.Web.UI.Page
    {
        private MM.Model.T_Users userModel;
        private int intNumber = 0;
        private bool bolFlag = true;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CurUser"] == null)
            {
                Response.Redirect("Login.aspx");
                return;
            }
            else
            {
                userModel = (MM.Model.T_Users)Session["CurUser"];
            }
            if (!IsPostBack)
            {
                inputDateFrom.Value = DateTime.Now.ToString("yyyy-MM-dd");
                inputDateTo.Value = DateTime.Now.ToString("yyyy-MM-dd");

                GVDataBind();

                if (userModel != null && userModel.RoleID.Equals("1"))
                {
                    btnDelete.Visible = true;
                }
            }
        }

        #region GV Bind
        private void GVDataBind()
        {
            bolFlag = true;

            string strSQL = "SELECT * FROM (SELECT a.mobile,count(a.mobile) as Rnum,c.ProvinceName,c.CityName FROM T_Receive a WITH(NOLOCK) left join T_DH c WITH(NOLOCK) on Left(a.mobile,7)=c.DH WHERE 1=1 ";

            string strWhere = string.Empty;
            string strProvinceName = MM.DBUtility.BLSqlData.GetProvinceNamebyQuickName(txtProvince.TextValue.Trim()).Replace("省", "").Replace("壮族自治区", "").Replace("回族自治区", "").Replace("维吾尔自治区", "").Replace("特别行政区", "").Replace("自治区", "");
            if (!string.IsNullOrEmpty(strProvinceName))
                strWhere += string.Format(" AND c.ProvinceName='{0}'", strProvinceName);
            if (!string.IsNullOrEmpty(txtmobile.Text.Trim()))
                strWhere += string.Format(" AND a.mobile LIKE '%{0}%'", txtmobile.Text.Trim());
            if ("1".Equals(ddlStatus.SelectedValue))
                strWhere += " AND (a.status='DELIVRD' OR a.status='0') ";
            else if ("2".Equals(ddlStatus.SelectedValue))
                strWhere += " AND a.status<>'DELIVRD' or status is null";
            if (!string.IsNullOrEmpty(inputDateFrom.Value) && !string.IsNullOrEmpty(inputDateTo.Value))
                strWhere += string.Format(" AND a.CreateTime BETWEEN '{0}' AND '{1}' ", inputDateFrom.Value, Convert.ToDateTime(inputDateTo.Value).AddDays(1).ToString("yyyy-MM-dd"));

            strSQL += strWhere;

            strSQL += " GROUP BY a.mobile,c.ProvinceName,c.CityName ) AS A";

            if (intNumber > 1)
                strSQL += string.Format(" WHERE Rnum>={0}", intNumber);

            AspNetPager1.RecordCount = DbHelperSql.GetCount("SELECT COUNT(1) FROM (" + strSQL + ") AS B");

            string strOrder = string.Format(" ORDER BY A.{0} {1}", ddlOrder.SelectedValue, ddlAD.SelectedValue);

            if (AspNetPager1.CurrentPageIndex == 1)
                strSQL = string.Format(strSQL.Replace("SELECT *", "SELECT TOP {0} * "), AspNetPager1.PageSize) + strOrder;
            else
                strSQL = string.Format("SELECT TOP {0} * FROM ({1}) AS F WHERE rn BETWEEN {2} AND {3}", AspNetPager1.PageSize, strSQL.Replace("SELECT *", string.Format("SELECT *,row_number() over({0}) rn ", strOrder)), (AspNetPager1.CurrentPageIndex - 1) * AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex * AspNetPager1.PageSize - 1);

            DataSet ds = DbHelperSql.Query(strSQL);
            GVinfo.DataSource = ds;
            GVinfo.DataBind();
            //ViewState["DataTemp"] = ds;
            lbCount.Text = "记录数：" + AspNetPager1.RecordCount;

            object o = DbHelperSql.GetSingle("SELECT count(*) FROM T_Receive a WITH(NOLOCK) left join T_DH c WITH(NOLOCK) on Left(a.mobile,7)=c.DH WHERE 1=1 " + strWhere);
            if (o != null)
            {
                lbRnumAll.Visible = true;
                lbRnumAll.Text = "总条数：" + o.ToString();
            }
            else lbRnumAll.Visible = false;
        }
        private void GVDataBindAll()
        {
            bolFlag = false;

            string strSQL = "SELECT * FROM (SELECT a.mobile,count(a.mobile) as Rnum,c.ProvinceName,c.CityName FROM T_Receive a WITH(NOLOCK) left join T_DH c WITH(NOLOCK)  on Left(a.mobile,7)=c.DH ";

            strSQL += " GROUP BY a.mobile,c.ProvinceName,c.CityName ) AS A";

            AspNetPager1.RecordCount = DbHelperSql.GetCount("SELECT COUNT(1) FROM (" + strSQL + ") AS B");

            string strOrder = string.Format(" ORDER BY A.{0} {1}", ddlOrder.SelectedValue, ddlAD.SelectedValue);


            if (AspNetPager1.CurrentPageIndex == 1)
                strSQL = string.Format(strSQL.Replace("SELECT *", "SELECT TOP {0} * "), AspNetPager1.PageSize) + strOrder;
            else
                strSQL = string.Format("SELECT TOP {0} * FROM ({1}) AS F WHERE rn BETWEEN {2} AND {3}", AspNetPager1.PageSize, strSQL.Replace("SELECT *", string.Format("SELECT *,row_number() over({0}) rn ", strOrder)), (AspNetPager1.CurrentPageIndex - 1) * AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex * AspNetPager1.PageSize - 1);

            DataSet ds = DbHelperSql.Query(strSQL);
            GVinfo.DataSource = ds;
            GVinfo.DataBind();
            //ViewState["DataTemp"] = ds;
            lbCount.Text = "记录数：" + AspNetPager1.RecordCount;

            object o = DbHelperSql.GetSingle("SELECT count(*) FROM T_Receive a WITH(NOLOCK) ");
            if (o != null)
            {
                lbRnumAll.Visible = true;
                lbRnumAll.Text = "总条数：" + o.ToString();
            }
            else lbRnumAll.Visible = false;
        }
        protected void GVinfo_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            //GVinfo.PageIndex = e.NewPageIndex;
            //GVinfo.DataSource = (DataSet)ViewState["DataTemp"];
            //GVinfo.DataBind();
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            if (bolFlag)
                GVDataBind();
            else
                GVDataBindAll();
        }
        #endregion

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(inputDateFrom.Value) && !string.IsNullOrEmpty(inputDateTo.Value))
                {
                    if (Convert.ToDateTime(inputDateFrom.Value) > Convert.ToDateTime(inputDateTo.Value))
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "创建时间From必须小于等于To！");
                        return;
                    }
                }
                intNumber = 0;
                if (!string.IsNullOrEmpty(txtNumber.Text.Trim()))
                {
                    try
                    {
                        intNumber = Convert.ToInt32(txtNumber.Text.Trim());
                    }
                    catch
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "条数>=必须为整数！");
                        return;
                    }
                }
                GVDataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnQueryAll_Click(object sender, EventArgs e)
        {
            try
            {
                inputDateFrom.Value = "";
                inputDateTo.Value = "";

                GVDataBindAll();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {

                if (!string.IsNullOrEmpty(inputDateFrom.Value) && !string.IsNullOrEmpty(inputDateTo.Value))
                {
                    if (Convert.ToDateTime(inputDateFrom.Value) > Convert.ToDateTime(inputDateTo.Value))
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "创建时间From必须小于等于To！");
                        return;
                    }
                }

                string strSQL = "DELETE FROM T_Receive a WHERE 1=1";
                string strWhere = string.Empty;
                if (!string.IsNullOrEmpty(txtmobile.Text.Trim()))
                    strWhere += string.Format(" AND a.mobile LIKE '%{0}%'", txtmobile.Text.Trim());
                if ("1".Equals(ddlStatus.SelectedValue))
                    strWhere += string.Format(" AND (a.status='DELIVRD' OR a.status='0')", txtmobile.Text.Trim());
                else if ("2".Equals(ddlStatus.SelectedValue))
                    strWhere += string.Format(" AND a.status<>'DELIVRD' or status is null", txtmobile.Text.Trim());
                if (!string.IsNullOrEmpty(inputDateFrom.Value) && !string.IsNullOrEmpty(inputDateTo.Value))
                    strWhere += string.Format(" AND a.CreateTime BETWEEN '{0}' AND '{1}' ", inputDateFrom.Value, Convert.ToDateTime(inputDateTo.Value).AddDays(1).ToString("yyyy-MM-dd"));

                strSQL = strSQL + strWhere;

                DbHelperSql.ExecuteSql(strSQL);

                MM.Common.Common.PageStartAlert(this.Page, "删除成功！");

                GVDataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void lbtnRnum_Click(object sender, EventArgs e)
        {
            try
            {
                LinkButton lbtn = (LinkButton)sender;
                string strArg = lbtn.CommandArgument;
                if (!string.IsNullOrEmpty(strArg))
                {
                    string strSQL = "SELECT a.spnum,a.content,a.feecode,a.mobile,a.status,a.CreateTime,c.ProvinceName,c.CityName FROM T_Receive a WITH(NOLOCK) left join T_DH c WITH(NOLOCK) on Left(a.mobile,7)=c.DH  WHERE 1=1 ";
                    strSQL += string.Format(" AND a.mobile='{0}' ", strArg);
                    if ("1".Equals(ddlStatus.SelectedValue))
                        strSQL += " AND (a.status='DELIVRD' OR a.status='0')";
                    else if ("2".Equals(ddlStatus.SelectedValue))
                        strSQL += " AND a.status<>'DELIVRD' or a.status is null";
                    if (!string.IsNullOrEmpty(inputDateFrom.Value) && !string.IsNullOrEmpty(inputDateTo.Value))
                        strSQL += string.Format(" AND a.CreateTime BETWEEN '{0}' AND '{1}' ", inputDateFrom.Value, Convert.ToDateTime(inputDateTo.Value).AddDays(1).ToString("yyyy-MM-dd"));
                    strSQL += " ORDER BY a.CreateTime DESC";

                    DataSet ds = DbHelperSql.Query(strSQL);
                    gvDetail.DataSource = ds;
                    gvDetail.DataBind();
                    ViewState["DataTempDetail"] = ds;
                    lbCountDetail.Text = "记录数：" + ds.Tables[0].Rows.Count;

                    divMain.Visible = false;
                    divDetail.Visible = true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void gvDetail_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                gvDetail.PageIndex = e.NewPageIndex;
                gvDetail.DataSource = (DataSet)ViewState["DataTempDetail"];
                gvDetail.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            try
            {
                divMain.Visible = true;
                divDetail.Visible = false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
